﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace DataAccess
{
    public class Access
    {
        //khai bao chuoi ket noi
        //private static string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DoiTuongChinhTri2013Test.accdb; Persist Security Info=False;Jet OLEDB:Database Password=123;";
        private static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DoiTuongChinhTri2013Test.mdb; Jet OLEDB:Database Password=Dat@gmail.123;";
        static OleDbConnection connection;
        public static void OpenConnection()
        {
            try
            {
                connection = new OleDbConnection(connectionString);
                connection.Open();
            }
            catch
            {
                connection = null;
            }
        }
        public static void CloseConnection()
        {
            if (connection != null)
            {
                connection.Close();
            }
        }
        public static DataTable ExcuQuery(string sql, params OleDbParameter[] para)
        {
            OpenConnection();
            DataTable dt = new DataTable();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = sql;
            foreach (var parameter in para)
            {
                command.Parameters.Add(parameter.ParameterName, parameter.OleDbType).Value = parameter.Value;
            }
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = command;
            adapter.Fill(dt);
            CloseConnection();
            return dt;
        }
        public static int ExcuNonQuery(string sql, params OleDbParameter[] para)
        {
            OpenConnection();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = sql;
            foreach (var parameter in para)
            {
                command.Parameters.Add(parameter.ParameterName, parameter.OleDbType).Value = parameter.Value;
            }
            int result = command.ExecuteNonQuery();
            CloseConnection();
            return result;
        }
    }
}
